<?php
/**
 * 
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-07-29 17:00:05
 * @version $Id$
 */

namespace app\mall\controller;

use think\Db;
use think\Request;
use think\Controller;

class Goodscate extends Controller {
    
    /**
     * 返回分类
     * @return [type] [description]
     */
    function index(){
    	$cat = CAT('goods_category',array('cate_id','cate_pid','cate_name','fullname'),'cate_status=1','listorder asc');
        $cat_tree = $cat->getTree(0);
    	foreach ($cat_tree as $k => $v) {
    		foreach ($v['_child'] as $kk => $vv) {
    			$cateId_arr = implode(',', array_column($vv['_child'],'cate_id'));
                $goods = [];
                if ($cateId_arr) {
                    $goods = Db::connect([],'cate')->field('cate.cate_id,g.goods_id')
                    ->table('sdzx_goods_category')->alias('cate')
                    ->join('sdzx_goods g','cate.cate_id=g.category_id')
                    ->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id')
                    ->where("cate.cate_id in ({$cateId_arr})  and sval.status=1")
                    ->group('cate.cate_id')
                    ->select();
                    $goods = array_column($goods,'cate_id');
                }
    			foreach ($vv['_child'] as $kkk => $vvv) {
                    if (empty($goods) || !in_array($vvv['cate_id'], $goods)) {
                        unset($cat_tree[$k]['_child'][$kk]['_child'][$kkk]);
                    }
    			}
                sort($cat_tree[$k]['_child'][$kk]['_child']);
    		}
    	}
    	return $this->success('success','',$cat_tree);
    }
}